﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MakeItWeb.Framework;
using System.Data;

namespace AllNations.UI
{
    public partial class ShoutOut : MakeItWebAuthenticatedUserPage, IDynamicPage
    {
        private Framework.ShoutoutConfiguration _Config = new Framework.ShoutoutConfiguration();
        private DataTable _Output;
        private bool _OlderPostAvailable = false;
        private DateTime _Now = DateTime.Now;

        private int PageSize
        {
            get { return _Config.PageSize; }
        }

        private int PageNum
        {
            get
            {
                if (ViewState["PageNum"] == null)
                    ViewState["PageNum"] = 1;

                return (int)ViewState["PageNum"];
            }
            set
            {
                ViewState["PageNum"] = value;
            }
        }

        private string SectionCd
        {
            get { return MakeItWebPage.GetQueryString("PageCd") ?? "Main"; }
        }

        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            _Config.Deserialize(CurrentHtmlPage.PageSettings);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            btSubmitShoutout.Click += new EventHandler(btSubmitShoutout_Click);
            if (!IsPostBack)
            {
                hidNewShoutoutId.Value = Guid.NewGuid().ToString();
            }
            _Output = GetPageData();
        }

        void btSubmitShoutout_Click(object sender, EventArgs e)
        {
            bool bSuccess = false;
            try
            {
                StoredProcArgs args = new StoredProcArgs();
                args["pShoutoutId"] = new Guid(hidNewShoutoutId.Value);
                args["pHtmlPageId"] = CurrentHtmlPage.HtmlPageId;
                args["pSectionCd"] = SectionCd;
                args["pUserName"] = User.Identity.Name;
                args["pContentTxt"] = txtContent.Text.Trim();
                GenericCud.ExecuteCud("proc_cm_SaveShoutout", args);

                bSuccess = true;
            }
            catch (Exception)
            {
            }
            finally
            {
                if (bSuccess)
                {
                    hidNewShoutoutId.Value = Guid.NewGuid().ToString();
                    txtContent.Text = string.Empty;
                    NewShoutoutViews.SelectedIndex = 0;
                    PageNum = 1;
                    _Output = GetPageData();
                }
            }
        }

        protected void imgMemberIcon_PreRender(object sender, EventArgs e)
        {
            (sender as Image).ImageUrl = GetCurrentUserIcon();
        }

        protected string GetCurrentUserIcon()
        {
            if (CurrentMember == null || string.IsNullOrEmpty(CurrentMember.IconFilenameTxt))
                return "~/Images/NoIcon.gif";
            return string.Format("{0}?t={1}", CurrentMember.IconFilenameTxt, _Now.Ticks);
        }

        protected string GetUserIcon(string sIconFilename)
        {
            if (string.IsNullOrEmpty(sIconFilename))
                return "~/Images/NoIcon.gif";

            return string.Format("{0}?t={1}", sIconFilename, _Now.Ticks);
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            rptShoutouts.DataSource = _Output;
            rptShoutouts.DataBind();
            CustomStyles.SelectedIndex = SectionCd == "YouthGroup" ? viewEnglish.Index : viewKorean.Index;
        }

        protected void btNewerPost_PreRender(object sender, EventArgs e)
        {
            (sender as LinkButton).Visible = PageNum > 1;
        }

        protected void btOlderPost_PreRender(object sender, EventArgs e)
        {
            (sender as LinkButton).Visible = _OlderPostAvailable;
        }

        protected void btNewerPost_Click(object sender, EventArgs e)
        {
            if (PageNum > 1)
                PageNum--;

            _Output = GetPageData();
        }

        protected void btOlderPost_Click(object sender, EventArgs e)
        {
            if (_OlderPostAvailable)
                PageNum++;

            _Output = GetPageData();
        }

        protected string formatContent(string sContent)
        {
            return sContent.Replace(Environment.NewLine, "<br/>");
        }

        protected string formatDisplayPostingTime(DateTime dtCreated)
        {
            TimeSpan tsDiff = DateTime.Now.Subtract(dtCreated);
            if (tsDiff < new TimeSpan(0, 1, 0))
                return "< 1m ago";
            else if (tsDiff < new TimeSpan(1, 0, 0))
                return string.Format("{0}m ago", tsDiff.Minutes, tsDiff.Minutes > 1 ? "s" : string.Empty);
            else if (tsDiff < new TimeSpan(1, 0, 0, 0))
                return string.Format("{0}h ago", tsDiff.Hours, tsDiff.Hours > 1 ? "s" : string.Empty);
            else
                return dtCreated.ToString("M/d/yyyy h:mm tt");
        }

        private DataTable GetPageData()
        {
            DataTable dtOut = null;

            int iPageStart = (PageNum - 1) * PageSize;
            int iPageEnd = iPageStart + PageSize;

            StoredProcArgs args = new StoredProcArgs();
            args["pHtmlPageId"] = CurrentHtmlPage.HtmlPageId;
            args["pSectionCd"] = SectionCd;
            args["pStartIdx"] = iPageStart;
            args["pEndIdx"] = iPageEnd;
            using (DataSet ds = GenericQry.GetDataSet("proc_cm_ListShotuout", args,  false))
            {
                dtOut = ds.Tables[0].Clone();

                for (int idx = 0; idx < PageSize && ds.Tables[0].Rows.Count > idx; idx++)
                    dtOut.Rows.Add(ds.Tables[0].Rows[idx].ItemArray);

                _OlderPostAvailable = ds.Tables[0].Rows.Count > PageSize;
            }

            return dtOut;
        }

        string IDynamicPage.GetPageConfigurationControl()
        {
            return "~/UI/Controls/ShoutoutConfiguration.ascx";
        }

        string IDynamicPage.PageTypeName
        {
            get { return "ShoutOut"; }
        }
    }
}